package com.neuedu.yyzx.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.neuedu.yyzx.common.CommonResult;
import com.neuedu.yyzx.common.util.TokenUtil;

import com.neuedu.yyzx.entity.User;
import com.neuedu.yyzx.service.IUserService;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 系统用户信息 前端控制器
 * </p>
 *
 * @author dya
 * @since 2021-04-27
 */
@RestController
@RequestMapping("//user")
public class UserController {
    @Resource
    IUserService userService;

    @RequestMapping(value = "/login")
    @ResponseBody
    public CommonResult login(@RequestHeader Map<String,Object> he, String username,String password) throws JsonProcessingException {
        QueryWrapper queryWrapper=new QueryWrapper();
        queryWrapper.eq("username",username);
        User user= userService.getOne(queryWrapper);
        if (user.getPassword().equals(password)){
//            String token= TokenUtil.sign(new User(username,password));
            String token= TokenUtil.sign(user);
            HashMap<String,Object> hs=new HashMap<>();
            hs.put("token",token);
            ObjectMapper objectMapper=new ObjectMapper();
            return CommonResult.success(objectMapper.writeValueAsString(hs));
        }else{
            return CommonResult.failed("账号或密码错误");
        }

    }

    @RequestMapping("/list")
    CommonResult list(Page page,User user){
        QueryWrapper queryWrapper=new QueryWrapper();
//        queryWrapper.eq("IS_DELETED",0);
        if(user!= null && StringUtils.isNotEmpty(user.getUsername())){
            queryWrapper.like("username",user.getUsername());
        }
        return CommonResult.success(userService.page(page,queryWrapper));
    }



    @RequestMapping("/getById")
    CommonResult getById(Integer id){
        return CommonResult.success(userService.getById(id));
    }

    @RequestMapping("add")
    CommonResult add(User user){
        return CommonResult.success(userService.saveOrUpdate(user));
    }

    @RequestMapping("/del")
    CommonResult del(Integer id){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("is_deleted",1);
        updateWrapper.eq("id",id);

        return CommonResult.success(userService.update(updateWrapper));
    }
    @RequestMapping("/back")
    CommonResult back(Integer id){
        UpdateWrapper updateWrapper = new UpdateWrapper();
        updateWrapper.set("is_deleted",0);
        updateWrapper.eq("id",id);

        return CommonResult.success(userService.update(updateWrapper));
    }

}
